<template>
  <div class="app-container">
    <!-- 加载状态 -->
    <el-loading v-if="loading" fullscreen text="加载中..."></el-loading>

    <div class="tabs">
      <div class="tabs-header">
        <span
          class="tabs-nav"
          :class="{ 'tabs-nav-selected': activeTab === index }"
          v-for="(tab, index) in tabs"
          @click="handleTabClick(index)"
          :key="index"
        >
          {{ tab }}
        </span>
      </div>

      <div class="tabs-content">
        <!-- 1. 关注留言（新增回复功能，与普通留言样式统一） -->
        <div v-show="activeTab === 0">
          <div
            class="text-details"
            v-for="(item, itemIndex) in typeList"
            :key="item.pnbId"
          >
            <el-row>
              <!-- 基础信息展示 -->
              <el-col :span="3"> 姓名:{{ item.studentName }} </el-col>
              <el-col :span="3">
                性别:{{ item.sex === "0" ? "男" : "女" }}
              </el-col>
              <el-col :span="10"> {{ item.dm }} </el-col>
              <el-col :span="4"> 电话:{{ item.stuMobile }} </el-col>
              <el-col :span="3"> 注册号:{{ item.regCode }} </el-col>

              <!-- 留言内容及回复区域（与普通留言样式统一） -->
              <el-col :span="24">
                <div
                  class="hover-card"
                  @mouseenter="showItemActions(itemIndex, null)"
                  @mouseleave="hideItemActions()"
                >
                  <!-- 主留言内容 -->
                  <div class="main-content">
                    {{ item.studentName }}:{{ item.noteCont }}
                  </div>

                  <!-- 主留言操作按钮（悬停显示） -->
                  <span
                    class="actions"
                    v-show="
                      hoveredItemIndex === itemIndex && !hoveredReplyIndex
                    "
                  >
                    <el-button
                      class="action-btn delete-btn"
                      type="text"
                      @click="handleDelete(item)"
                    >
                      <i class="fa fa-trash"></i> 删除
                    </el-button>
                    <el-button
                      class="action-btn edit-btn"
                      type="text"
                      @click="handleBack(item)"
                    >
                      <i class="fa fa-pencil"></i> 回复
                    </el-button>
                  </span>

                  <!-- 留言时间 -->
                  <div class="create-time">{{ item.createTime }}</div>

                  <!-- 回复内容展示 -->
                  <div v-if="item.noteReply" class="main-reply">
                    {{ item.noteReply.createBy }}回复@{{ item.studentName }}：{{
                      item.noteReply.replyCont
                    }}
                    <span @click="getReplly(item.pnbId)" class="reply-count">
                      共{{ item.replyCount }}条回复▼
                    </span>
                    <div class="create-time">
                      {{ item.noteReply.createTime }}
                    </div>
                  </div>

                  <!-- 回复列表 -->
                  <div
                    v-for="(reply, replyIndex) in item.data"
                    :key="reply.replyId || replyIndex"
                    class="reply-item"
                    @mouseenter="showItemActions(itemIndex, replyIndex)"
                    @mouseleave="hideItemActions()"
                  >
                    <span class="reply-author">{{ reply.createBy }}</span
                    >回复@{{ reply.replyPerson }}：
                   
                    <span class="reply-content">{{ reply.replyCont }}</span>
                    <div class="create-time">{{ reply.createTime }}</div>

                    <!-- 回复操作按钮 -->
                    <span
                      class="actions"
                      v-show="
                        hoveredItemIndex === itemIndex &&
                        hoveredReplyIndex === replyIndex
                      "
                    >
                      <el-button
                        class="action-btn delete-btn"
                        type="text"
                        @click="handleDeleteReply(reply)"
                      >
                        <i class="fa fa-trash"></i> 删除
                      </el-button>
                      <el-button
                        class="action-btn edit-btn"
                        type="text"
                        @click="handleReplyToReply(reply)"
                      >
                        <i class="fa fa-pencil"></i> 回复
                      </el-button>
                    </span>
                  </div>
                  <!-- 查看更多/收起按钮 -->
                  <div v-if="item.data.length > 5" class="reply-toggle-btn">
                    <el-button
                      type="text"
                      @click="toggleReplyDisplay(item)"
                      class="toggle-btn"
                    >
                      {{
                        item.showAllReplies
                          ? "收起"
                          : `查看更多(${item.data.length - 5}条)`
                      }}
                    </el-button>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>

          <!-- 分页组件 -->
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>

        <!-- 2. 普通留言（保持原有功能，样式与关注留言统一） -->
        <div v-show="activeTab === 1">
          <!-- 原有普通留言内容（结构不变，样式与关注留言统一） -->
          <div
            class="text-details"
            v-for="(item, itemIndex) in typeList"
            :key="item.pnbId"
          >
            <el-row>
              <el-col :span="3"> 姓名:{{ item.studentName }} </el-col>
              <el-col :span="3">
                性别:{{ item.sex === "0" ? "男" : "女" }}
              </el-col>
              <el-col :span="10"> {{ item.dm }} </el-col>
              <el-col :span="4"> 电话:{{ item.stuMobile }} </el-col>
              <el-col :span="3"> 注册号:{{ item.regCode }} </el-col>
              <el-col :span="24">
                <div
                  class="hover-card"
                  @mouseenter="showItemActions(itemIndex, null)"
                  @mouseleave="hideItemActions()"
                >
                  {{ item.studentName }}:{{ item.noteCont }}

                  <!-- 主留言操作按钮 -->
                  <span
                    class="actions"
                    v-show="
                      hoveredItemIndex === itemIndex && !hoveredReplyIndex
                    "
                  >
                    <el-button
                      class="action-btn delete-btn"
                      type="text"
                      @click="handleDelete(item)"
                    >
                      <i class="fa fa-trash"></i> 删除
                    </el-button>
                    <el-button
                      class="action-btn edit-btn"
                      type="text"
                      @click="handleBack(item)"
                    >
                      <i class="fa fa-pencil"></i> 回复
                    </el-button>
                  </span>

                  <div class="create-time">{{ item.createTime }}</div>

                  <!-- 回复内容展示 -->
                  <div v-if="item.noteReply" class="main-reply">
                    {{ item.noteReply.createBy }}回复@{{ item.studentName }}：{{
                      item.noteReply.replyCont
                    }}
                    <span @click="getReplly(item.pnbId)" class="reply-count">
                      共{{ item.replyCount }}条回复▼
                    </span>
                    <div class="create-time">
                      {{ item.noteReply.createTime }}
                    </div>
                  </div>

                  <!-- 回复列表 -->
                  <div
                    v-for="(reply, replyIndex) in item.data"
                    :key="reply.replyId"
                    class="reply-item"
                    @mouseenter="showItemActions(itemIndex, replyIndex)"
                    @mouseleave="hideItemActions()"
                  >
                    <span class="reply-author">{{ reply.createBy }}</span
                    >回复@{{ reply.replyPerson }}：
                    <!-- <span class="reply-target"></span> -->
                    <span class="reply-content">{{ reply.replyCont }}</span>
                    <div class="create-time">{{ reply.createTime }}</div>

                    <!-- 回复操作按钮 -->
                    <span
                      class="actions"
                      v-show="
                        hoveredItemIndex === itemIndex &&
                        hoveredReplyIndex === replyIndex
                      "
                    >
                      <el-button
                        class="action-btn delete-btn"
                        type="text"
                        @click="handleDeleteReply(reply)"
                      >
                        <i class="fa fa-trash"></i> 删除
                      </el-button>
                      <el-button
                        class="action-btn edit-btn"
                        type="text"
                        @click="handleReplyToReply(reply)"
                      >
                        <i class="fa fa-pencil"></i> 回复
                      </el-button>
                    </span>
                  </div>
                  <!-- 查看更多/收起按钮 -->
                  <div v-if="item.data.length > 5" class="reply-toggle-btn">
                    <el-button
                      type="text"
                      @click="toggleReplyDisplay(item)"
                      class="toggle-btn"
                    >
                      {{
                        item.showAllReplies
                          ? "收起"
                          : `查看更多(${item.data.length - 5}条)`
                      }}
                    </el-button>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>

          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </div>
    </div>

    <!-- 回复弹窗（通用，两种留言共用） -->
    <el-dialog title="回复" :visible.sync="openReply">
      <el-form :model="form" ref="replyForm">
        <el-form-item
          label="留言回复"
          prop="replyCont"
          :rules="[
            { required: true, message: '请输入回复内容', trigger: 'blur' },
          ]"
        >
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入回复内容"
            v-model="form.replyCont"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openReply = false">取 消</el-button>
        <el-button type="primary" @click="submitReply">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  noteboardList,
  delNoteboard,
  replies,
  getReplies,
  parentReplies,
  delReply,
} from "@/api/psychological/message";
import Pagination from "@/components/Pagination";

export default {
  name: "MessageBoard",
  components: { Pagination },
  dicts: ["sys_normal_disable"],
  data() {
    return {
      activeTab: 0,
      loading: true,
      tabs: ["关注留言", "普通留言"],
      typeList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        pnbType: "G", // G-关注留言，P-普通留言
      },
      form: { replyCont: "" },
      bndId: "", // 当前回复的留言ID
      replyToId: "", // 被回复的回复ID
      // 悬停状态管理
      hoveredItemIndex: null,
      hoveredReplyIndex: null,
      total: 0,
      openReply: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表数据（兼容两种留言类型） */
    getList() {
      this.loading = true;
      noteboardList(this.queryParams)
        .then((response) => {
          this.typeList = response.rows;
          this.total = response.total;
          // 初始化回复列表字段（确保两种留言数据结构一致）
          this.typeList.forEach((item) => {
            if (!item.data) item.data = []; // 回复列表默认空数组
            if (!item.replyCount) item.replyCount = 0; // 回复数默认0
          });
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /** 标签切换（重置页码并加载数据） */
    handleTabClick(index) {
      if (this.activeTab === index) return;
      this.activeTab = index;
      this.queryParams = {
        ...this.queryParams,
        pnbType: index === 1 ? "P" : "G",
        pageNum: 1, // 切换标签重置页码
      };
      this.getList();
    },

    /** 打开回复弹窗（主留言回复） */
    handleBack(data) {
      this.openReply = true;
      this.bndId = data.pnbId;
      this.replyToId = ""; // 主留言回复无需回复ID
      this.form.replyCont = "";
      this.$nextTick(() => {
        this.$refs.replyForm?.clearValidate(); // 清除验证
      });
    },
    /** 切换回复显示状态（展开/收起） */
    toggleReplyDisplay(item) {
      item.showAllReplies = !item.showAllReplies;
    },

    /** 回复某条回复 */
    handleReplyToReply(reply) {
      this.openReply = true;
      this.bndId = reply.pnbId; // 关联主留言ID
      this.replyToId = reply.pnrId; // 被回复的回复ID
      this.form.replyCont = "";
      this.$nextTick(() => {
        this.$refs.replyForm?.clearValidate();
      });
    },

    /** 提交回复（兼容主留言和回复的回复） */
    submitReply() {
      this.$refs.replyForm.validate((valid) => {
        if (valid) {
          const params = { replyCont: this.form.replyCont };
          // 根据是否有replyToId判断是回复主留言还是回复
          const request = this.replyToId
            ? parentReplies(this.replyToId, params)
            : replies(this.bndId, params);

          request.then((res) => {
            if (res.code === 200) {
              this.$message.success("回复成功");
              this.openReply = false;
              this.getList(); // 刷新列表
            } else {
              this.$message.error(res.msg || "回复失败");
            }
          });
        }
      });
    },

    /** 获取回复列表（两种留言共用） */
    getReplly(pnbId) {
      getReplies(pnbId).then((response) => {
        const targetItem = this.typeList.find((item) => item.pnbId === pnbId);
        if (targetItem) {
          targetItem.data = response.data || []; // 赋值回复列表
        }
      });
    },

    /** 显示操作按钮 */
    showItemActions(itemIndex, replyIndex) {
      this.hoveredItemIndex = itemIndex;
      this.hoveredReplyIndex = replyIndex;
    },

    /** 隐藏操作按钮 */
    hideItemActions() {
      this.hoveredItemIndex = null;
      this.hoveredReplyIndex = null;
    },

    /** 删除主留言（两种留言共用） */
    handleDelete(row) {
      this.$confirm(`是否确认删除${row.studentName}的留言？`, "确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return delNoteboard(row.pnbId);
        })
        .then(() => {
          this.$message.success("删除成功");
          this.getList();
        })
        .catch(() => {});
    },

    /** 删除回复（两种留言共用） */
    handleDeleteReply(reply) {
      this.$confirm("是否确认删除该回复？", "确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return delReply(reply.pnrId);
        })
        .then(() => {
          this.$message.success("删除成功");
          this.getList();
        })
        .catch(() => {});
    },

    /** 搜索重置 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        pnbType: this.activeTab === 1 ? "P" : "G",
      };
      this.getList();
    },
  },
};
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f9fafc;
}

/* 标签页样式优化 */
.tabs-header {
  margin-bottom: 20px;
  border-bottom: 1px solid #e6e6e6;
  padding-bottom: 5px;
  background-color: #fff;
  padding: 10px 20px;
  border-radius: 4px 4px 0 0;
}

.tabs-nav {
  display: inline-block;
  margin-right: 30px;
  cursor: pointer;
  padding: 8px 5px;
  position: relative;
  font-size: 14px;
  transition: color 0.3s;
}

.tabs-nav:hover {
  color: #1890ff;
}

.tabs-nav-selected {
  color: #1890ff;
  font-weight: 500;
}

.tabs-nav-selected::after {
  content: "";
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #1890ff;
}

.tabs-content {
  background-color: #fff;
  padding: 20px;
  border-radius: 0 0 4px 4px;
  min-height: 300px;
}

/* 留言卡片样式 */
.text-details {
  background-color: #f5f7fa;
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 6px;
  transition: box-shadow 0.3s;
}

.text-details:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

/* 主留言内容样式 */
.hover-card {
  position: relative;
  padding: 10px 0;
  border-top: 1px dashed #e6e6e6;
  margin-top: 10px;
}

.hover-card:first-child {
  border-top: none;
  margin-top: 0;
}

.main-content {
  font-size: 14px;
  line-height: 1.6;
}

/* 回复区域样式（两种留言统一） */
.main-reply {
  margin: 10px 0;
  padding-left: 15px;
  border-left: 2px solid #e1f3ff;
  font-size: 13px;
}

.reply-item {
  padding: 8px 0;
  margin-left: 20px;
  border-left: 2px solid #e6e6e6;
  padding-left: 15px;
  position: relative;
  font-size: 13px;
}

/* 回复作者/目标样式 */
.reply-author {
  color: #1890ff;
  font-weight: 500;
}

.reply-target {
  color: #f56c6c;
  font-weight: 500;
}

.reply-content {
  margin-left: 5px;
}

/* 操作按钮样式优化 */
.actions {
  margin-left: 10px;
  display: inline-block;
}

.action-btn {
  padding: 0 5px !important;
  margin-left: 5px !important;
  font-size: 12px !important;
}

.delete-btn {
  color: #f56c6c !important;
}

.delete-btn:hover {
  color: #f24957 !important;
}

.edit-btn {
  color: #1890ff !important;
}

.edit-btn:hover {
  color: #0e86d4 !important;
}

/* 时间和回复数样式 */
.create-time {
  color: #8c8c8c;
  font-size: 12px;
  margin-top: 5px;
  margin-bottom: 5px;
  display: block;
}

.reply-count {
  color: #1890ff;
  cursor: pointer;
  font-size: 12px;
  margin-left: 8px;
}

.reply-count:hover {
  text-decoration: underline;
}

/* 悬停动画优化 */
.actions {
  opacity: 0;
  transition: opacity 0.3s ease, transform 0.3s ease;
  transform: translateY(2px);
}

.hover-card:hover .actions,
.reply-item:hover .actions {
  opacity: 1;
  transform: translateY(0);
}

/* 分页样式 */
::v-deep .pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 加载状态覆盖 */
::v-deep .el-loading-mask {
  background-color: rgba(255, 255, 255, 0.8);
}
</style>